package com.zmn.plat.services.impl.mc.staff;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.string.StringUtil;

/**
 * 散列密码加密解密码
 *
 * @author duanzuocai
 * @version v1.0
 * @since 2019/1/21 10:44
 */
@Service
public class PlatPasswordEncoder {

    private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 校验密码
     *
     * @param password
     *            要校验的密码字符串
     * @param salt
     *            盐
     * @param hashPassword
     *            已散列的原始密码
     * @return
     */
    public Boolean checkPassword(String password, String salt, String hashPassword) {
        if (StringUtil.isBlank(password) || StringUtil.isBlank(salt) || StringUtil.isBlank(hashPassword)) {
            return false;
        }

        String saltPassword = getSaltPassword(password, salt);

        return passwordEncoder.matches(saltPassword, hashPassword);
    }

    /**
     * 根据盐值生成默认密码
     *
     * @param salt
     *            盐值
     * @return
     */
    public String defaultPassword(String salt) {
        if (StringUtil.isBlank(salt)) {
            return null;
        }
        return generatePassword(GlobalConsts.ZMN_STAFF_DEFAULT_PASSWORD, salt);
    }

    /**
     * 生成密码
     *
     *
     * @param password
     *            未加密的原始密码
     * @param salt
     *            盐值
     * @return
     */
    public String generatePassword(String password, String salt) {
        if (StringUtil.isBlank(password)) {
            return null;
        }

        String saltPassword = getSaltPassword(password, salt);

        return passwordEncoder.encode(saltPassword);
    }

    /**
     * 拼接盐密码
     *
     * @param password
     *            未加密的原始密码
     * @param salt
     *            盐值
     * @return
     */
    private String getSaltPassword(String password, String salt) {
        return new StringBuffer(password).append(":").append(salt).toString();
    }
}
